package com.glory.wxelectricitypda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dothantech.printer.IDzPrinter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.AddCarrierDataAdapter;
import com.glory.wxelectricitypda.adapter.MatOutListAdapter;
import com.glory.wxelectricitypda.adapter.MatListAdapter;
import com.glory.wxelectricitypda.adapter.MatNumListAdapter;
import com.glory.wxelectricitypda.bean.MatEntity;
import com.glory.wxelectricitypda.bean.MlotAppointmentListEntity;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.FreeApi_DialogUtils;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MaterialPrePareActivity extends PrinterActivity {

    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.ltmlotids)
    FreeUI_ClearEditText ltmlotids;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.etMLot)
    FreeUI_ClearEditText etMLot;
    @BindView(R.id.rvMLotList)
    RecyclerView rvMLotList;
    @BindView(R.id.rlv_ltmlotids)
    RecyclerView rlv_ltmlotids;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llmmlot)
    LinearLayout llmmlot;
    @BindView(R.id.tvPreNum)
    TextView tvPreNum;
    @BindView(R.id.tvPrint)
    TextView tvPrint;


    private AddCarrierDataAdapter materielModelAdapter;
    private List<String> ltmlotidsList = new ArrayList<>();
    private MatListAdapter matListAdapter;
    private MatOutListAdapter matOutListAdapter;
    private String maid = "";
    private double matQty = -1;
    private double standarQty = 0.0;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_prepare;
    }

    @Override
    protected void initView() {
        super.initView();
        rvLotList.setLayoutManager(new LinearLayoutManager(MaterialPrePareActivity.this));
        rvLotList.setItemAnimator(new DefaultItemAnimator());
        rvLotList.addItemDecoration(new DividerItemDecoration(MaterialPrePareActivity.this, 1));

        matListAdapter = new MatListAdapter(null);
        rvLotList.setAdapter(matListAdapter);

        rvMLotList.setLayoutManager(new LinearLayoutManager(MaterialPrePareActivity.this));
        rvMLotList.setItemAnimator(new DefaultItemAnimator());
        rvMLotList.addItemDecoration(new DividerItemDecoration(MaterialPrePareActivity.this, 1));
        matOutListAdapter = new MatOutListAdapter(null);
        rvMLotList.setAdapter(matOutListAdapter);

        rlv_ltmlotids.setLayoutManager(new LinearLayoutManager(this));
        rlv_ltmlotids.setItemAnimator(new DefaultItemAnimator());
        rlv_ltmlotids.addItemDecoration(new DividerItemDecoration(this, 1));
        materielModelAdapter = new AddCarrierDataAdapter(null, getSupportFragmentManager());
        materielModelAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielModelAdapter.isFirstOnly(true);
        rlv_ltmlotids.setAdapter(materielModelAdapter);

    }

    @Override
    protected void onPrinterConnected(IDzPrinter.PrinterAddress printer) {
        super.onPrinterConnected(printer);
        // 调用LPAPI对象的getPrinterInfo方法获得当前连接的打印机信息
        String txt = getResources().getString(R.string.printer) + getResources().getString(R.string.chinesecolon);
        txt += api.getPrinterInfo().deviceName + "\n";
        txt += api.getPrinterInfo().deviceAddress;
        com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils.getConfirmDialog(MaterialPrePareActivity.this, "确定",txt, new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {

            }
        }).show(getSupportFragmentManager(),"DIALOG");
//        tvPrint.setVisibility(View.VISIBLE);
//        tvPrint.setText(txt);

    }

    @Override
    protected void initData() {
        super.initData();

        initEdit(ltmlotids,s->{

            boolean containsDuplicate = false;
            for (int i = 0; i < ltmlotidsList.size(); i++) {
                if (s.equals(ltmlotidsList.get(i))){
                    containsDuplicate = true;
                }
            }
            if (containsDuplicate){
                showToast("该归还料号批次已存在",false);
                return;
            }

            JSONObject map = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            try {
                map.put("ACTIONTYPE", "ACTIONBACKMLOTQUERY");
                map.put("MLOTID", s);
                jsonObject.put("Data",map);
                jsonObject.put("MessageName","EUIT.MLOTAPPLYOUT");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                    new TypeToken<ResponseBean<Object>>() {
                    }.getType(), getSupportFragmentManager(), this) {
                @Override
                public void onSuccess(Response<ResponseBean<Object>> response) {
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        ltmlotidsList.add(s);
                        materielModelAdapter.setNewData(ltmlotidsList);
                        ltmlotids.setText("");
                        new Handler().postDelayed(() -> {
                            ltmlotids.requestFocus();
                        }, 500);
                    }
                }
                @Override
                public void onError(Response<ResponseBean<Object>> response) {
                    super.onError(response);
                    loadError(response.getException(), "MLOTAPPLYOUT");
                }
            });


        });

        initEdit(etLot, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {



                ltmlotidsList.clear();
                ltmlotids.setText("");
                materielModelAdapter.setNewData(null);
                llmmlot.setVisibility(View.GONE);

                JSONObject map = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                try {
                    map.put("ACTIONTYPE", "QUERYAPPLY");
                    map.put("LOTID", s);
                    jsonObject.put("Data",map);
                    jsonObject.put("MessageName","EUIT.MLOTAPPLYOUT");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<MlotAppointmentListEntity>>(
                        new TypeToken<ResponseBean<MlotAppointmentListEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            MlotAppointmentListEntity body = response.body().getBody();
                            if (body.getMLOTAPPOINTMENTLIST().isEmpty()){
                                showToast("暂无物料信息",false);
                                return;
                            }

                            showMatDialog(body.getMLOTAPPOINTMENTLIST());

                        }
                    }
                    @Override
                    public void onError(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "MLOTAPPLYOUT");
                    }
                });
            }
        });


        initEdit(etMLot, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {
                if (maid.isEmpty()){
                    showToast("未获取到预约单号！",false);
                    return;
                }

                if (s.contains("|")) {
                    s = s.replace("|", ",").split(",")[2];
                }

                JSONObject map = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                try {
                    map.put("ACTIONTYPE", "ACTIONADDMLOT");
                    map.put("MLOTID", s);
                    map.put("MAID", maid);
                    JSONArray jsonArray = new JSONArray(new Gson().toJson(matOutListAdapter.getData()));
                    map.put("CURRENTOUTLIST",jsonArray);
                    jsonObject.put("Data",map);
                    jsonObject.put("MessageName","EUIT.MLOTAPPLYOUT");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<MlotAppointmentListEntity>>(
                        new TypeToken<ResponseBean<MlotAppointmentListEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            MlotAppointmentListEntity body = response.body().getBody();
                            if (body.getOUTLIST().isEmpty()){
                                showToast("暂无物料信息",false);
                                return;
                            }

                            double qty = 0;
                            for (MatEntity datum : matOutListAdapter.getData()) {
                                qty += datum.getMAINQTY();
                            }

                            double mQty = 0;
                            for (MatEntity matEntity : body.getOUTLIST()) {
                                mQty += matEntity.getMAINQTY();
                            }

                            if ((qty + mQty) - matQty > 0.01){
                                showToast("物料数量不匹配",false);
                                return;
                            }

                            Log.d("aaa",body.getOUTLIST().get(0).getSTANDERQTY());
                            if (standarQty == 0.0){
//                                showToast("数据异常 standarQty为0 请联系管理员检查数据；",false);
                               com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils.getConfirmDialog(MaterialPrePareActivity.this, "确定","数据异常 standarQty为0 请联系管理员检查数据；", new FreeUI_CommonCallback() {
                                   @Override
                                   public void onSuccess() {

                                   }
                               }).show(getSupportFragmentManager(),"DIALOG");
                            }else {
                                for (MatEntity matEntity : body.getOUTLIST()) {
                                    matEntity.setSTANDERQTY(String.valueOf(matEntity.getMAINQTY() / standarQty));
                                }
                            }

                            matOutListAdapter.addData(body.getOUTLIST());
                            etMLot.setText("");
                        }
                    }
                    @Override
                    public void onError(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "ACTIONADDMLOT");
                    }
                });

            }
        });
    }

    private void showMatDialog(List<MlotAppointmentListEntity.MlotAppointmentEntity> mlotappointmentlist) {
        View inflate = View.inflate(this, R.layout.dialog_material_prepare, null);
        FreeUI_GeneralFragmentDialog freeDialog = FreeApi_DialogUtils.getFreeDialog(inflate);
        RecyclerView rvMatNumList = inflate.findViewById(R.id.rvMatNumList);
        rvMatNumList.setLayoutManager(new LinearLayoutManager(MaterialPrePareActivity.this));
        rvMatNumList.setItemAnimator(new DefaultItemAnimator());
        rvMatNumList.addItemDecoration(new DividerItemDecoration(MaterialPrePareActivity.this, 1));
        MatNumListAdapter adapter = new MatNumListAdapter(mlotappointmentlist, new OnItemMatClick() {
            @Override
            public void setOnItemMatClickListener(int position) {

                if (mlotappointmentlist.get(position).getMaType().equals("XH"))

                freeDialog.dismiss();
                matQty = mlotappointmentlist.get(position).getMlotMainQty();
                standarQty = Double.parseDouble(mlotappointmentlist.get(position).getStandardMainQty());
                tvPreNum.setText(String.valueOf(matQty));
                getMaterialInfo(mlotappointmentlist.get(position).getMaId());


                if (!mlotappointmentlist.get(position).getLtReason().isEmpty() || mlotappointmentlist.get(position).getMaType().equals("XH")){

                    llmmlot.setVisibility(View.GONE);
                }else {
                    llmmlot.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(() -> {
                        ltmlotids.requestFocus();
                    }, 500);
                }

            }
        });
        rvMatNumList.setAdapter(adapter);
        freeDialog.show(getSupportFragmentManager(),"MAT_DIALOG");
    }

    private void getMaterialInfo(String maId) {
        maid = maId;
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "QUERYMAT");
            map.put("MAID", maId);
            jsonObject.put("Data",map);
            jsonObject.put("MessageName","EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<MlotAppointmentListEntity>>(
                new TypeToken<ResponseBean<MlotAppointmentListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    MlotAppointmentListEntity body = response.body().getBody();
                    if (body.getMATLIST().isEmpty()){
                        showToast("暂无物料信息",false);
                        return;
                    }
                    matListAdapter.setNewData(body.getMATLIST());
                }
            }
            @Override
            public void onError(Response<ResponseBean<MlotAppointmentListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("预约发料");
        freeUI_titleView.setRightListener("发料", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double qty = 0;
                for (MatEntity datum : matOutListAdapter.getData()) {
                    qty += datum.getMAINQTY();
                }

                if (qty - matQty > 0.01){
                    showToast("物料数量不匹配",false);
                    return;
                }
                if (llmmlot.getVisibility() == View.VISIBLE) {
                    if (materielModelAdapter.getData().size()<=0){
                        showToast("请扫描归还料号批次", false);
                        return;
                    }
                }
                JSONObject map = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                try {
                    map.put("ACTIONTYPE", "OUT");
                    map.put("MAID", maid);
                    JSONArray jsonArray = new JSONArray(new Gson().toJson(matOutListAdapter.getData()));
                    map.put("OUTLIST",jsonArray);

                    StringBuilder stringBuilder = new StringBuilder();
                    for (String element : materielModelAdapter.getData()) {
                        stringBuilder.append(element).append(";");
                    }
                    if (stringBuilder.length() > 0) {
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }
                    String concatenatedString = stringBuilder.toString();
                    map.put("LTMLOTIDS",concatenatedString);

                    jsonObject.put("Data",map);
                    jsonObject.put("MessageName","EUIT.MLOTAPPLYOUT");
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                        new TypeToken<ResponseBean<Object>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<Object>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            showToast("预约发料成功",true);
//                            finish();
                            for (MatEntity datum : matOutListAdapter.getData()) {
                                if (!datum.getUDF().getISNEEDPRINT().equals("N")){
                                    printMaterialPrePare(datum);
                                }
                            }
//                            finish();
//                            MatEntity matEntity = matOutListAdapter.getData().get(0);
//                            matEntity.getMATERIALNAME();  //料号
//                            matEntity.getMAINQTY();  //数量
//                            matEntity.getUDF().getFLOOR_LIFE_EXPIRE();//过期时间
//                            matEntity.getUDF().getWAKEUP_END_DATE();//启用时间
//                            matEntity.getMATERIALDESC();//名称
//                            matEntity.getMLOTID();//批号

                        }

                    }
                    @Override
                    public void onError(Response<ResponseBean<Object>> response) {
                        super.onError(response);
                        loadError(response.getException(), "MLOTAPPLYOUT");
                    }
                });


            }
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    public interface OnItemMatClick{
        void setOnItemMatClickListener(int position);
    }

}
